package com.wj.tool.config;


import com.wj.domain.vo.BookVO;
import com.wj.service.BookCacheService;
import com.wj.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Configuration
@Slf4j
public class UpdateBookConfig {

    @Resource
    private BookService bookService;

    @Resource
    private BookCacheService bookCacheService;

    //秒 分 时 日 月 周
    @Scheduled(cron = "0 0 12 * * ?") //更新时间
    public void update(){
        updateFiction();
    }
    private void updateFiction(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        log.info("定时开始更新小说"+sdf.format(now));
        //获取所有小说
        List<BookVO> list=bookService.getBookList();
        //循环更新小说
        for (BookVO bookVO:list){
            bookService.updateBook(bookVO.getId(),bookVO.getBookUrl());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.info("线程休眠异常");
                e.printStackTrace();
            }
        }

    }

    //秒 分 时 日 月 周
    @Scheduled(cron = "0 0 15 * * ?") //更新时间
    public void createTxt(){
        createBookFile();
    }
    private void createBookFile(){
        log.info("开始缓存小说");
        //获取所有小说
        List<BookVO> list=bookCacheService.getCacheBookList();
        //循环更新小说
        for (BookVO bookVO:list){
            bookCacheService.createBookFile(bookVO.getId(), bookVO.getBookName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.info("线程休眠异常");
                e.printStackTrace();
            }
        }
    }
}
